// 判断是否为对象 ，注意 null 也是对象
const isObject = (val) => val !== null && typeof val === 'object';

/* 
reactive函数
*/
export function reactive(target) {
  // 如果target不是对象, 直接返回原值
  if (!isObject(target)) return target

  // 准备一个处理器对象
  const handler = {
    // 监视读取
    get (target, prop, receiver){
      console.log(`监视读取${prop}属性`)
      console.log('收集/追踪依赖') // track

      const result = Reflect.get (target, prop, receiver)
      return isObject(result) ? reactive(result) : result
    },
    // 监视修改和添加
    set (target, prop, value, receiver) {
      console.log(`监视修改或添加${prop}属性`)
      // 得到旧值
      const oldValue = Reflect.get (target, prop, receiver)
      let result = true
      if (oldValue!=value) {
        result = Reflect.set(target, prop, value, receiver)
        if (result) {
          console.log('派发/触发更新') // trigger
        }
      }
      return result
    },
    // 监视删除
    deleteProperty (target, prop) {
      console.log(`监视删除${prop}属性`)
      const result = Reflect.deleteProperty(target, prop)
      if (result) {
        console.log('派发/触发更新2') // trigger
      }
      return result
    }
  }

  // 返回一个代理对象
  return new Proxy(target, handler)
}